<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%"
  >
    <el-row :gutter="20">
      <el-col :span="3">
        <p>产品名称:</p>
      </el-col>
      <el-col :span="6"><el-input v-model="goods.name" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3">
        <p>产品型号:</p>
      </el-col>
      <el-col :span="6"><el-input v-model="goods.model" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3"><p>分类:</p></el-col>
      <el-col :span="6"><el-cascader
        :options="categoryOptions"
        v-model="goods.categoryId"
        :show-all-levels="false"
        change-on-select
      ></el-cascader></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3"><p>副标题:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.caption" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3"><p>销售价:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.price" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3"><p>重量:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.weight" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="3"><p>单位:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.unit" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="4"><el-checkbox v-model="goods.hasSpec" :disabled="!!goods.sn">是否有规格</el-checkbox></el-col>
      <el-col :span="4"><el-checkbox v-model="goods.groupon">是否可拼团</el-checkbox></el-col>
      <el-col :span="4"><el-checkbox v-model="goods.delivery">是否有物流</el-checkbox></el-col>
      <el-col :span="4"><el-checkbox v-model="goods.marketable">是否上架</el-checkbox></el-col>
    </el-row>
    <el-row :gutter="20" v-if="!goods.hasSpec">
      <el-col :span="3"><p>供货价:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.cost" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <el-row :gutter="20" v-if="goods.groupon">
      <el-col :span="3"><p>拼团人数:</p></el-col>
      <el-col :span="6">
        <el-input-number v-model="goods.grouponCount" :min="1" :max="6"></el-input-number>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-if="!goods.hasSpec">
      <el-col :span="3"><p>库存:</p></el-col>
      <el-col :span="6"><el-input v-model="goods.stock" placeholder="请输入内容"></el-input></el-col>
    </el-row>
    <template v-for="(specification, index) in goods.specificationGroup">
      <div class="spec-container">
        <el-row :gutter="20" v-if="goods.hasSpec">
          <el-col :span="3"><p>规格组:</p></el-col>
          <el-col :span="6">
            <!--<el-input v-model="specification.specificationName" @blur="onSpecChange"></el-input>-->
            <el-select v-model="specification.specificationName" clearable placeholder="请选择" @change="onSpecChange">
              <el-option
                v-for="item in specGroupOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="specification.specificationEntries"
              multiple
              placeholder="请选择"
              @change="onSpecChange">
              <el-option
                v-for="item in specValueArrParse(specification.specificationName)"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"><el-button @click.prevent="removeSpec(index)">删除</el-button></el-col>
          <!--<el-col :span="2"><el-button @click="$router.push({ name: 'demo-echarts' })">test</el-button></el-col>-->
        </el-row>
      </div>
    </template>

    <el-button @click="addSpec" v-if="goods.hasSpec&&!goods.sn">新增规格组</el-button>

    <el-table
      :data="specTableData"
      border
      style="width: 100%"
      class="specTable"
      v-if="goods.hasSpec">
      <el-table-column
        :prop="header.value"
        :label="headerParse(header.name)"
        v-for="(header, index) in specHeader"
        :key="index">
      </el-table-column>

      <el-table-column
        prop="cost"
        label="供货价">
        <template slot-scope="scope">
          <el-input v-model="scope.row.cost" placeholder="供货价"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="销售价">
        <template slot-scope="scope">
          <el-input v-model="scope.row.price" placeholder="销售价"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="price"
        label="拼团价"
        v-if="goods.groupon"
      >
        <template slot-scope="scope">
          <el-input v-model="scope.row.groupPrice" placeholder="拼团价"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="stock"
        label="库存">
        <template slot-scope="scope">
          <el-input v-model="scope.row.stock" placeholder="库存"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="默认">
        <template slot-scope="scope">
          <el-radio v-model="productDefault" :label="scope.$index">&nbsp</el-radio>
        </template>
      </el-table-column>
      <el-table-column
        prop="enable"
        label="启用">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.enable"></el-checkbox>
        </template>
      </el-table-column>

    </el-table>

    <div style="width: 500px">
      <template v-for="(para, index) in paraGroup">
        <el-row :gutter="20">
          <el-col :span="4"><p>参数名</p></el-col>
          <el-col :span="6"><el-input v-model="para.name"></el-input></el-col>
          <el-col :span="4"><el-button @click="addSubPara(index)">新增</el-button></el-col>
          <el-col :span="4"><el-button @click="removeParaGroup(index)">删除</el-button></el-col>
        </el-row>
        <template v-for="(entry, subindex) in para.entries">
          <el-row :gutter="20">
            <el-col :span="4"><p></p></el-col>
            <el-col :span="4"><el-input v-model="entry.name"></el-input></el-col>
            <el-col :span="6"><el-input v-model="entry.value"></el-input></el-col>
            <el-col :span="4"><el-button @click="removeSubPara(index, subindex)">删除</el-button></el-col>
          </el-row>
        </template>
      </template>

      <el-button @click="addParaGroup()">新增参数</el-button>

    </div>

    <div class="product-list">
      商品图片:<el-upload
      :action="uploadUrl"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="goods.productImages"
      :on-success="successHandle"
      :on-error="errorHandle"
      :limit="pilimit"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    </div>

    <div class="product-list">
      介绍图片:<el-upload
      :action="uploadUrl"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="introHandleRemove"
      :file-list="goods.introProductImages"
      :on-success="introSuccessHandle"
      :on-error="errorHandle"
      :limit="iilimit"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    </div>

    <el-button @click="addGoods()">提交</el-button>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </el-dialog>
</template>

<script>
  /* eslint-disable eqeqeq,no-self-compare */

  // 笛卡尔积
  function cartesianProductOf (array) {
    function addTo (current, args) {
      var i, copy
      var rest = args.slice(1)
      var isLast = !rest.length
      var result = []
      for (i = 0; i < args[0].length; i++) {
        copy = current.slice()
        copy.push(args[0][i])
        if (isLast) {
          result.push(copy)
        } else {
          result = result.concat(addTo(copy, rest))
        }
      }
      return result
    }
    return addTo([], array)
  }
  export default {
    data () {
      return {
        uploadUrl: window.SITE_CONFIG.baseUrl + '/file/upload',
        visible: false,
        categoryOptions: [],
        paraGroup: [],
        specroupOptions: [],
        goods: {
          price: 0,
          cost: 0,
          name: '',
          model: '',
          caption: '',
          groupon: false,
          grouponCount: 0,
          weight: 0,
          unit: '',
          stock: 0,
          hasSpec: false,
          delivery: true,
          marketable: true,
          categoryId: [],
          productImages: [],
          introProductImages: [],
          specificationGroup: [],
          productDefault: 0
        },
        specHeader: [
        ],
        specTableData: [],
        productImageUrlArr: [],
        introImageUrlArr: [],
        pilimit: 6,
        iilimit: 6,
        dialogImageUrl: '',
        dialogVisible: false,
        productDefault: 0
      }
    },
    computed: {
      // 计算属性的 getter
      reversedMessage: function () {
        // `this` 指向 vm 实例
        return this.message.split('').reverse().join('')
      }
    },
    filters: {
    },
    mounted () {
    },
    methods: {
      init: function (id) {
        this.visible = true
        this.categoryOptions = []
        this.paraGroup = []
        this.specGroupOptions = []
        this.goods = {
          price: 0,
          cost: 0,
          name: '',
          model: '',
          caption: '',
          weight: 0,
          unit: '',
          stock: 0,
          hasSpec: false,
          delivery: true,
          marketable: true,
          categoryId: [],
          productImages: [],
          introProductImages: [],
          specificationGroup: [],
          productDefault: 0
        }
        this.specHeader = []
        this.specTableData = []
        this.productImageUrlArr = []
        this.introImageUrlArr = []
        this.$http({
          url: this.$http.adornUrl(`/sys/productCategory/tree`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categoryOptions = data.productCategroyTree || []
            console.log(data.productCategroyTree)
          }
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/sys/specification/tree`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.specGroupOptions = data.specificationTree || []
              console.log('specGroupOptions >>>>>>>>>>>>>>>>>>>>>> ', this.specGroupOptions)
            }
          }).then(() => {
            if (!id) {
              console.log('out >>>>>>>>>>>>>>')
              return
            }
            console.log('in >>>>>>>>>>>>>>')
            this.$http({
              url: this.$http.adornUrl(`/sys/goods/info/${id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                // 介绍图
                if (data.goodsInfo.introduction && data.goodsInfo.introduction != '') {
                  let arr = data.goodsInfo.introduction.split(',')
                  data.goodsInfo.introProductImages = []
                  let i = 0
                  for (let imgItem of arr) {
                    data.goodsInfo.introProductImages.push({name: i + '', url: imgItem})
                    i++
                  }
                } else {
                  data.goodsInfo.introduction = []
                }

                // 产品图
                if (data.goodsInfo.productImages && data.goodsInfo.productImages != '') {
                  let arr = data.goodsInfo.productImages.split(',')
                  data.goodsInfo.productImages = []
                  let i = 0
                  for (let imgItem of arr) {
                    data.goodsInfo.productImages.push({name: i + '', url: imgItem})
                    i++
                  }
                } else {
                  data.goodsInfo.productImages = []
                }

                if (data.goodsInfo.parameterValues && data.goodsInfo.parameterValues != '') {
                  this.paraGroup = JSON.parse(data.goodsInfo.parameterValues) || []
                }

                if (data.goodsInfo.specificationItems && data.goodsInfo.specificationItems != '') {
                  data.goodsInfo.specificationGroup = JSON.parse(data.goodsInfo.specificationItems) || []
                }

                let treePath = data.treePath.substring(1, data.treePath.length - 1)
                let treePathArr = []
                let temArr = treePath.split(',')
                for (let item of temArr) {
                  treePathArr.push(parseInt(item))
                }
                data.goodsInfo.categoryId = treePathArr
                data.goodsInfo.delivery = data.goodsInfo.isDelivery
                data.goodsInfo.marketable = data.goodsInfo.isMarketable
                data.goodsInfo.groupon = ((data.goodsInfo.campaign & 1) == 1)
                this.goods = data.goodsInfo
                console.log('this.goods >>>>>>>>>>>>>>>>>>>>>> ', this.goods)
                if (this.goods.specificationItems && this.goods.specificationItems != '') {
                  this.goods.hasSpec = true
                  let specJson = JSON.parse(this.goods.specificationItems)
                  let i = 0
                  for (let obj of specJson) {
                    if (obj && obj.specificationName && obj.specificationName !== '') {
                      this.specHeader.push({name: obj.specificationName, value: 'spec' + i})
                      i++
                    }
                  }

                  let defaultIdx = 0
                  for (let product of this.goods.productList) {
                    if (product.isDefault == true) {
                      this.productDefault = defaultIdx
                    }
                    let pSpecValArr = product.specificationValues.split(',')
                    let i = 0
                    for (let item of pSpecValArr) {
                      if (!item || item == '') {
                        continue
                      }
                      product['spec' + i] = this.specValueParse(item)
                      i++
                    }
                    product.specIds = product.specificationValues
                    this.specTableData.push(product)
                    defaultIdx++
                  }
                } else {
                  let first = this.goods.productList[0] || []
                  this.goods.cost = first.cost || 0
                  this.goods.stock = first.stock || 0
                }
              }

              console.log('specTableData=', this.specTableData)
            })
          })
        })
      },
      addParaGroup: function () {
        this.paraGroup.push({name: '', entries: []})
      },
      addSubPara: function (index) {
        this.paraGroup[index].entries.push({name: '', value: ''})
      },
      removeSubPara: function (index, subindex) {
        this.paraGroup[index].entries.splice(subindex, 1)
      },
      removeParaGroup: function (index) {
        this.paraGroup.splice(index, 1)
      },
      headerParse: function (value) {
        for (var option of this.specGroupOptions) {
          if (option.value.toString() === value.toString()) {
            return option.label
          }
        }
        return ''
      },
      specValueParse: function (specValue) {
        for (var option of this.specGroupOptions) {
          for (var item of option.children) {
            if (item.value == specValue) {
              return item.label || ''
            }
          }
        }
        return ''
      },
      specValueArrParse: function (groupValue) {
        for (var option of this.specGroupOptions) {
          if (option.value === groupValue) {
            return option.children
          }
        }
        return ''
      },
      errorHandle (err, file, fileList) {
        this.$message.error(err)
      },
      // 上传成功
      successHandle (response, file, fileList) {
        this.goods.productImages.push({name: file.name || '', url: response.url || ''})
      },
      // 上传成功
      introSuccessHandle (response, file, fileList) {
        this.goods.introProductImages.push({name: file.name || '', url: response.url || ''})
      },
      introHandleRemove (file, fileList) {
        for (let idx in this.goods.introProductImages) {
          let item = this.goods.introProductImages[idx]
          if (item.url == file.url) {
            this.goods.introProductImages.splice(idx, 1)
          }
        }
      },
      handleRemove (file, fileList) {
        for (let idx in this.goods.productImages) {
          let item = this.goods.productImages[idx]
          if (item.url == file.url) {
            this.goods.productImages.splice(idx, 1)
          }
        }
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      addGoods () {
        var productImageUrlArr = []
        for (let item of this.goods.productImages) {
          productImageUrlArr.push(item.url)
        }
        var introImageUrlArr = []
        for (let item of this.goods.introProductImages) {
          introImageUrlArr.push(item.url)
        }
        this.goods.introImageUrlArr = introImageUrlArr
        this.goods.productImageUrlArr = productImageUrlArr
        this.goods.productDefault = this.productDefault
        this.$http({
          url: this.$http.adornUrl(`/sys/goods/add`),
          method: 'post',
          data: this.$http.adornData({ goods: this.goods, paraList: this.paraGroup, specList: this.specTableData })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      onSpecChange () {
        let i = 0
        this.specHeader = []
        let specValues = []
        for (let obj of this.goods.specificationGroup) {
          if (obj && obj.specificationName && obj.specificationName !== '') {
            this.specHeader.push({name: obj.specificationName, value: 'spec' + i})
            i++
          }
          let entries = obj.specificationEntries
          let specEntry = []
          for (let entry of entries) {
            specEntry.push(entry)
          }
          if (specEntry.length > 0) {
            specValues.push(specEntry)
          }
        }
        this.specTableData = []
        if (specValues && specValues.length > 0) {
          let productValues = cartesianProductOf(specValues)
          for (let specArr of productValues) {
            let specVal = {}
            let specItemIdx = 0
            let specItemArr = []
            for (let specItem of specArr) {
              let specItemLabel = ''
              for (let svoitem of this.specGroupOptions) {
                let svo = svoitem.children
                for (let svosub of svo) {
                  if (svosub.value === specItem) {
                    specItemLabel = svosub.label
                    break
                  }
                }
              }
              specVal['spec' + specItemIdx] = specItemLabel
              specItemArr.push(specItem)
              specItemIdx++
            }
            this.specTableData.push(Object.assign({
              cost: 0,
              price: 0,
              groupPrice: 0,
              enable: false,
              stock: 0,
              specIds: ',' + specItemArr.splice(',') + ','
            }, specVal))
          }
        }
      },
      removeSpec (index) {
        this.goods.specificationGroup.splice(index, 1)
        this.onSpecChange()
      },
      addSpec () {
        this.goods.specificationGroup.push({specificationName: '',
          specificationEntries: []})
      }
    }
  }
</script>

<style lang="scss">
  .spec-container {
    width: 800px;
    p {
      margin-top: 10px;
      margin-left: 18px;
    }
  }

  .specTable {
    margin-top: 10px;
  }

  .product-list {
    margin-top: 10px;
  }


</style>
